package InRecord.controller;

import org.apache.commons.io.IOUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
public class TestController {
    public static String conf_filename = "/etc/fdfs/client.conf";

    @RequestMapping("testDownload")
    @ResponseBody
    public Object testDownload(){
        try {

            ClientGlobal.init(conf_filename);

            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;

            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            //group1M00/00/00/wKgBDFvBnviALiwMAAAAAgAAAAA007.txt
            byte[] b = storageClient.download_file("group1", "M00/00/00/wKgBDFu7HUOAb681AAAACjY4GO4196.jpg");
            System.out.println(b);
            IOUtils.write(b, new FileOutputStream("/opt/"+ UUID.randomUUID().toString()+".jpg"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    @RequestMapping("testUpload")
    @ResponseBody
    public Object testUpload(){
        String path = "";
        try {
            ClientGlobal.init(conf_filename);

            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;

            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
//          NameValuePair nvp = new NameValuePair("age", "18");
            String fileIds[] = storageClient.upload_file(new byte[]{(byte)0xFF, (byte)0xFF}, "txt", null);
            path = fileIds[0] + "_" + fileIds[1];
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return path;
    }

}
